using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using CoreManager.Core.Middleware;
using CoreManager.Repository.DbContext;

namespace CoreManager.Core.Extensions
{
    /// <summary>
    /// 应用构建器扩展
    /// </summary>
    public static class ApplicationBuilderExtensions
    {
        /// <summary>
        /// 使用请求日志中间件
        /// </summary>
        public static IApplicationBuilder UseRequestLogging(this IApplicationBuilder app)
        {
            return app.UseMiddleware<RequestLoggingMiddleware>();
        }

        /// <summary>
        /// 配置Swagger文档
        /// </summary>
        public static IApplicationBuilder UseSwaggerDocumentation(this IApplicationBuilder app, IHostEnvironment environment)
        {
            if (environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "CoreManager API V1");
                    c.RoutePrefix = string.Empty; // 设置Swagger UI为根路径
                    c.DocExpansion(Swashbuckle.AspNetCore.SwaggerUI.DocExpansion.None);
                    c.DisplayRequestDuration();
                    c.EnableDeepLinking();
                    c.EnableFilter();
                    c.ShowExtensions();
                    c.ShowCommonExtensions();
                });
            }

            return app;
        }

        /// <summary>
        /// 初始化数据库
        /// </summary>
        public static IApplicationBuilder InitializeDatabase(this IApplicationBuilder app)
        {
            using var scope = app.ApplicationServices.CreateScope();
            var dbContext = scope.ServiceProvider.GetRequiredService<CoreManagerDbContext>();
            
            try
            {
                dbContext.InitializeDatabaseAsync().Wait();
                Console.WriteLine("数据库初始化成功");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"数据库初始化失败: {ex.Message}");
                // 在生产环境中可能需要更严格的错误处理
                if (Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Production")
                {
                    throw;
                }
            }

            return app;
        }

        /// <summary>
        /// 配置中间件管道
        /// </summary>
        public static IApplicationBuilder ConfigureMiddlewarePipeline(this IApplicationBuilder app, IHostEnvironment environment)
        {
            // 1. 全局异常处理（最先注册，最后执行）
            // 注意：全局异常处理中间件应该在所有其他中间件之前注册
            // 这样才能捕获所有后续中间件和控制器中的异常
            // 不再使用默认的 UseDeveloperExceptionPage 和 UseExceptionHandler
            // 统一使用自定义的全局异常处理中间件
            
            // 2. HTTPS重定向
            app.UseHttpsRedirection();

            // 3. 静态文件
            app.UseStaticFiles();

            // 4. 路由
            app.UseRouting();

            // 5. 关联ID（在认证之前）
            app.UseCorrelationId();

            // 6. CORS（在认证之前）
            app.UseCors("DefaultPolicy");

            // 7. 认证
            app.UseAuthentication();

            // 8. 授权
            app.UseAuthorization();

            // 9. 请求日志（在业务逻辑之前）
            app.UseRequestLogging();

            return app;
        }
    }
}